package com.canto.wanna.user.services.impl;

import com.canto.access.pojo.bo.AccessUserDetails;
import com.canto.common.services.DataService;
import com.canto.wanna.user.dao.UserDao;
import com.canto.wanna.user.pojo.doo.ResourceDO;
import com.canto.wanna.user.pojo.doo.UserDO;
import com.canto.wanna.user.pojo.entity.User;
import com.canto.wanna.user.pojo.query.UserQuery;
import com.canto.wanna.user.pojo.query.UserRoleRelationQuery;
import com.canto.wanna.user.services.UserRoleRelationService;
import com.canto.wanna.user.services.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户基本信息ServiceImpl
 *
 * @Author jsryin
 * @Date 2021/7/8
 */
@Service
@Transactional(readOnly = true)
public class UserServiceImpl extends DataService<UserDao> implements UserService {

    @Autowired
    private UserRoleRelationService userRoleRelationService;


    @Override
    public UserDO get(UserQuery query) {
        return super.get(query);
    }

    public List<UserDO> findList(UserQuery userQuery) {
        return super.findList(userQuery);
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public long save(User user) {
        return super.save(user);
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public long delete(User user) {
        return super.delete(user);
    }

    @Override
    public AccessUserDetails loadUserByUsername(UserQuery userQuery) {
        List<UserDO> userList = this.findList(userQuery);
        if (CollectionUtils.isEmpty(userList)) {
            throw new UsernameNotFoundException("登录名或密码错误");
        } else if (userList.size() > 1) {
            throw new UsernameNotFoundException("登录名或密码错误");
        }
        UserDO userDO = userList.get(0);
        if (userDO == null || !StringUtils.isNoneBlank(userDO.getId())) {
            throw new UsernameNotFoundException("登录名或密码错误");
        }
        UserRoleRelationQuery userRoleRelationQuery = new UserRoleRelationQuery();
        userRoleRelationQuery.setUserId(userDO.getId());
        List<ResourceDO> resourceList = userRoleRelationService.findResourceList(userRoleRelationQuery);


        return new AccessUserDetails(userDO, resourceList);
    }

}
